import 'package:dailoz/data/loading_data.dart';
import 'package:dailoz/data/page_data.dart';
import 'package:dailoz/service/jpush_service/jpush_service.dart';
import 'package:dailoz/service/user_service/user_service.dart';
import 'package:dailoz/theme/dark/dark_theme.dart';
import 'package:dailoz/theme/light/light_theme.dart';
import 'package:dailoz/utils/network_check.dart';
import 'package:dailoz/view_model/add_page_view_model.dart';
import 'package:dailoz/view_model/user.dart';
import 'package:dailoz/views/add_page.dart';
import 'package:dailoz/views/modify_page.dart';
import 'package:dailoz/views/settings_page.dart';
import 'package:dailoz/views/task_tag_detail.dart';
import 'package:dailoz/views/task_type_detail.dart';
import 'package:dailoz/views/home.dart';
import 'package:dailoz/views/login.dart';
import 'package:dailoz/views/sign_up.dart';
import 'package:dailoz/views/splash.dart';
import 'package:dailoz/widgets/dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:ui' as ui;

import 'generated/l10n.dart';

void main() {
  // 开启布局线
  debugPaintSizeEnabled = false;
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations(
          [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown])
      .then((_) => {realRunApp()});
  JPushService.jPushInit();
}

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

void realRunApp() async {
  final prefs = await SharedPreferences.getInstance();
  final brightness = ui.window.platformBrightness;
  NetWorkCheck.check();
  // 判断用户之前是否登录
  bool isLogin = await UserService.getIsLogin();
  if (isLogin) {
    int? userPhone = prefs.getInt("user-phone");
    String? password = prefs.getString("user-password");
    User userInfo = User(phoneNum: userPhone, password: password);
    await UserService.login(userInfo);
  }
  runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider(
        create: (context) => PageData(),
      ),
      ChangeNotifierProvider(
        create: (context) => WebSocketData(),
      ),
      ChangeNotifierProvider(
        create: (context) => AddPageViewModel(),
      ),
    ],
    child: MyApp(isLogin: isLogin, prefs: prefs, brightness: brightness),
  ));
  // }
}

class MyApp extends StatefulWidget {
  const MyApp(
      {super.key,
      required this.isLogin,
      required this.prefs,
      required this.brightness});

  final bool isLogin;
  final SharedPreferences prefs;
  final Brightness brightness;

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  Brightness? _brightness;

  @override
  void initState() {
    super.initState();
    _brightness = widget.brightness;
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangePlatformBrightness() {
    super.didChangePlatformBrightness();
    setState(() {
      _brightness = ui.window.platformBrightness;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<PageData>(builder: (context, pageData, child) {
      return MaterialApp(
        title: 'Flutter Demo',
        navigatorKey: navigatorKey,
        localizationsDelegates: const [
          S.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
        ],
        debugShowCheckedModeBanner: false,
        supportedLocales: [
          widget.prefs.getString("languageCode") == null
              ? const Locale("zh", "CN")
              : Locale.fromSubtags(
                  languageCode: widget.prefs.getString("languageCode")!,
                  countryCode: widget.prefs.getString("countryCode")!),

          // const Locale("zh", "CN"),
          // ...S.delegate.supportedLocales,
        ],
        theme: _brightness == Brightness.dark
            ? DarkTheme.darkTheme
            : LightTheme.lightTheme,
        initialRoute: widget.isLogin ? Home.id : Splash.id,
        routes: {
          Splash.id: (context) => const Splash(),
          Login.id: (context) => const Login(),
          SignUp.id: (context) => const SignUp(),
          Home.id: (context) => const Home(),
          TaskTypeDetail.id: (context) => const TaskTypeDetail(),
          AddPage.id: (context) => const AddPage(),
          HtmlDialog.id: (context) => const HtmlDialog(),
          ModifyPage.id: (context) => const ModifyPage(),
          SettingPage.id: (context) => const SettingPage(),
          TaskTagDetail.id: (context) => const TaskTagDetail(),
        },
      );
    });
  }
}
